package com.aji.biomarker.service.impl;

import com.aji.allcommon.result.Result;
import com.aji.biomarker.domain.Compound;
import com.aji.biomarker.domain.Correspondence;
import com.aji.biomarker.domain.Reference;
import com.aji.biomarker.domain.Species;
import com.aji.biomarker.domain.vo.BiomarkerVo;
import com.aji.biomarker.mapper.*;
import com.aji.biomarker.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.opencsv.CSVParser;
import com.opencsv.CSVParserBuilder;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;
import com.opencsv.exceptions.CsvValidationException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Service
@RequiredArgsConstructor
public class BiomarkerServiceImpl extends ServiceImpl<BiomarkerMapper, BiomarkerVo> implements BiomarkerService{

    private final CompoundService compoundService;
    private final SpeciesService speciesService;
    private final ReferenceService referenceService;
    private final CorrespondenceService correspondenceService;

    @Transactional
    public Result importCsv(MultipartFile file) {
        List<Compound> compounds = new ArrayList<>();
        List<Species> speciesList = new ArrayList<>();
        List<Reference> references = new ArrayList<>();
        List<Correspondence> correspondences = new ArrayList<>();

        // 取文件名去掉扩展名作为 origin_category
        String originalFilename = file.getOriginalFilename();
        String originCategory = (originalFilename != null && originalFilename.contains("."))
                ? originalFilename.substring(0, originalFilename.lastIndexOf('.'))
                : originalFilename;

        try (
                InputStreamReader isr = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr)
        ) {
            CSVParser parser = new CSVParserBuilder()
                    .withSeparator(',')
                    .withQuoteChar('"')
                    .withIgnoreQuotations(false)
                    .build();

            CSVReader reader = new CSVReaderBuilder(br)
                    .withSkipLines(1)
                    .withCSVParser(parser)
                    .build();

            String[] cols;
            int row = 2;

            while ((cols = reader.readNext()) != null) {
                for (int i = 0; i < cols.length; i++) {
                    if (cols[i] != null) {
                        cols[i] = cols[i].replaceAll("^\"|\"$", "").trim();
                    }
                }

                if (cols.length < 8) {
                    return Result.error("第 " + row + " 行列数不正确！（实际列数：" + cols.length + "）");
                }

                // Compound（以 ename 唯一标识）
                Compound c = compoundService.getOne(
                        new LambdaQueryWrapper<Compound>().eq(Compound::getEname, cols[0])
                );
                if (c == null) {
                    c = new Compound();
                    c.setEname(cols[0]);
                    c.setCname(cols[1]);
                    c.setFormula(cols[2]);
                    try {
                        c.setWeight(Double.valueOf(cols[3]));
                    } catch (NumberFormatException e) {
                        c.setWeight(null);
                    }
                    c.setCas(cols[4]);
                    compoundService.save(c);
                }
                compounds.add(c);

                // Species（origin + remark 唯一）
                Species s = speciesService.getOne(
                        new LambdaQueryWrapper<Species>()
                                .eq(Species::getOriginCategory, originCategory)
                                .eq(Species::getOrigin, cols[5])
                                .eq(Species::getRemark, cols[6])
                );
                if (s == null) {
                    s = new Species();
                    s.setOriginCategory(originCategory); // 从文件名设置
                    s.setOrigin(cols[5]);
                    s.setRemark(cols[6]);
                    speciesService.save(s);
                }
                speciesList.add(s);

                // Reference（reference 唯一）
                Reference r = referenceService.getOne(
                        new LambdaQueryWrapper<Reference>()
                                .eq(Reference::getReference, cols[7])
                );
                if (r == null) {
                    r = new Reference();
                    r.setReference(cols[7]);
                    referenceService.save(r);
                }
                references.add(r);

                row++;
            }

            // 构造对应关系
            for (int i = 0; i < compounds.size(); i++) {
                Correspondence corr = new Correspondence();
                corr.setCompoundId(compounds.get(i).getId());
                corr.setSpeciesId(speciesList.get(i).getId());
                corr.setReferenceId(references.get(i).getId());
                correspondences.add(corr);
            }
            correspondenceService.saveBatch(correspondences);

        } catch (IOException | CsvValidationException e) {
            e.printStackTrace();
            return Result.error("导入失败：" + e.getMessage());
        }

        return Result.success("导入成功，共 " + compounds.size() + " 条数据（来源分类：" + originCategory + "）");
    }




//    @Autowired
//    BiomarkerMapper biomarkerMapper;
//    @Override
//    public IPage<BiomarkerVo> listTakeName(Page<BiomarkerVo> biomarkerVoPage, LambdaQueryWrapper<BiomarkerVo> biomarkerVoLambdaQueryWrapper) {
//        return biomarkerMapper.listTakeName(biomarkerVoPage,biomarkerVoLambdaQueryWrapper);
//    }
}
